package org.gcb.core.windows;

import java.util.Collection;
import java.util.logging.Logger;
import org.gcb.core.model.EDefense;
import org.gcb.core.model.Toon;
import org.gcb.core.ui.nodes.DefenseChildFactory;
import org.openide.util.Lookup.Result;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.ImageUtilities;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(dtd = "-//org.gcb.core.windows//Defenses//EN",
autostore = false)
public final class DefensesTopComponent extends TopComponent implements ExplorerManager.Provider, LookupListener{
    private static ExplorerManager explorerManager = new ExplorerManager();
    private static DefensesTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    private static final String PREFERRED_ID = "DefensesTopComponent";

    private Lookup.Result<Toon> result = null;

    public DefensesTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(DefensesTopComponent.class, "CTL_DefensesTopComponent"));
        setToolTipText(NbBundle.getMessage(DefensesTopComponent.class, "HINT_DefensesTopComponent"));
//        setIcon(ImageUtilities.loadImage(ICON_PATH, true));
        associateLookup(ExplorerUtils.createLookup(explorerManager, getActionMap()));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        listView1 = new org.openide.explorer.view.ListView();
        jPanel1 = new javax.swing.JPanel();
        lblAC = new javax.swing.JLabel();
        lblFort = new javax.swing.JLabel();
        lblRef = new javax.swing.JLabel();
        lblWill = new javax.swing.JLabel();

        setLayout(new java.awt.BorderLayout());
        add(listView1, java.awt.BorderLayout.CENTER);

        jPanel1.setLayout(new java.awt.GridLayout());

        org.openide.awt.Mnemonics.setLocalizedText(lblAC, org.openide.util.NbBundle.getMessage(DefensesTopComponent.class, "DefensesTopComponent.lblAC.text")); // NOI18N
        jPanel1.add(lblAC);

        org.openide.awt.Mnemonics.setLocalizedText(lblFort, org.openide.util.NbBundle.getMessage(DefensesTopComponent.class, "DefensesTopComponent.lblFort.text")); // NOI18N
        jPanel1.add(lblFort);

        org.openide.awt.Mnemonics.setLocalizedText(lblRef, org.openide.util.NbBundle.getMessage(DefensesTopComponent.class, "DefensesTopComponent.lblRef.text")); // NOI18N
        jPanel1.add(lblRef);

        org.openide.awt.Mnemonics.setLocalizedText(lblWill, org.openide.util.NbBundle.getMessage(DefensesTopComponent.class, "DefensesTopComponent.lblWill.text")); // NOI18N
        jPanel1.add(lblWill);

        add(jPanel1, java.awt.BorderLayout.PAGE_END);
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel lblAC;
    private javax.swing.JLabel lblFort;
    private javax.swing.JLabel lblRef;
    private javax.swing.JLabel lblWill;
    private org.openide.explorer.view.ListView listView1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link #findInstance}.
     */
    public static synchronized DefensesTopComponent getDefault() {
        if (instance == null) {
            instance = new DefensesTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the DefensesTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized DefensesTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(DefensesTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof DefensesTopComponent) {
            return (DefensesTopComponent) win;
        }
        Logger.getLogger(DefensesTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID
                + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        result = WindowManager.getDefault().findTopComponent("ToonListingTopComponent").getLookup().lookupResult(Toon.class);
        result.addLookupListener(this);
        resultChanged(new LookupEvent(result));
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    Object readProperties(java.util.Properties p) {
        if (instance == null) {
            instance = this;
        }
        instance.readPropertiesImpl(p);
        return instance;
    }

    private void readPropertiesImpl(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return explorerManager;
    }

    @Override
    public void resultChanged(LookupEvent ev) {
        Lookup.Result r = (Result) ev.getSource();
        Collection<Toon> toons = r.allInstances();
        if(toons.isEmpty())
            return;
        Toon t = toons.iterator().next();
        AbstractNode aNode = new AbstractNode(Children.create(new DefenseChildFactory(t.getDefenses()), true));

        lblAC.setText("AC: "+t.getDefenses().get(EDefense.AC).getScore());
        lblFort.setText("Fort: "+t.getDefenses().get(EDefense.FORT).getScore());
        lblRef.setText("Ref: "+t.getDefenses().get(EDefense.REF).getScore());
        lblWill.setText("Will: "+t.getDefenses().get(EDefense.WILL).getScore());
        explorerManager.setRootContext(aNode);
    }
}
